﻿define([
  'models/abmManagers/userManager',
  'models/abmManagers/preferenceManager',
  'text!templates/abmManagers/abmBaseTmp.html',
  'text!templates/abmManagers/abmFormTmp.html',
  'text!templates/abmManagers/preference/auxiliar/entityPrefEdit.html',
  'text!templates/abmManagers/preference/auxiliar/preferenceItem.html',
], function (userModel, prefModel, BaseTmp, FormTmp, UniqTmp, PrefTmp) {
    var view = Backbone.View.extend({
        el: $("#main"),
        _uId: "",
        _user: {},
        _prevSel: {companyId: "", moduleId: ""},
        render: function () {
            $("#mainLoading").show();
            $("div[data-rel='abm-user']").remove();
            var usrMod = new userModel();
            var prefMod = new prefModel();
            var _this = this;
            this._uId = $.uuid();

            usrMod.GetUser(this.options.userId, function (dataUser) {
                _this._user = dataUser;

                prefMod.ListPrefModules(function (dataPrefModules) {
                    var baseTemplate = Handlebars.compile(BaseTmp);
                    var formTemplate = Handlebars.compile(FormTmp);
                    var uniqTemplate = Handlebars.compile(UniqTmp);

                    //var comboTemplate = Handlebars.compile(ComboTmp);

                    var dataBaseTemplate = {
                        id: _this._uId,
                        dataRel: "abm-user", // cuidado, ref en js
                        tmpClass: "user-pref-edit", // cuidado, ref en css
                        title: translate("_editUserPreferences")
                    };
                    var dataUniqTemplate = {
                        prefModule: dataPrefModules
                    };
                    //var company = { company: dataUser.userCompanies };

                    var html = baseTemplate(dataBaseTemplate);
                    var html2 = formTemplate();
                    //var htmlCombo = comboTemplate(company);
                    var html3 = uniqTemplate(dataUniqTemplate);

                    _this.$el.append(html);
                    $("div[data-id='" + _this._uId + "']").find("div.abm-content").append(html2);
                    //$("div[data-id='" + _this._uId + "']").find("div.form-content").append(htmlCombo);
                    $("div[data-id='" + _this._uId + "']").find("div.form-content").append(html3);

                    postRender(_this.$el.find("div[data-id='" + _this._uId + "']"));

                    _this.firstValues();
                    
                    _this.addHandlers();
                    $("#mainLoading").hide();
                });
            });
        },
        firstValues: function () {
            var _this = this;

            _this._prevSel = {
                companyId: __currentSession.companyId,
                moduleId: $("div[data-id='" + _this._uId + "']").find("div.pref-module-selection select").val()
            }
            // nuevo cargar valores iniciales
            var prefMod = new prefModel();
            prefMod.List(undefined, function (dataPref) {
                if (_this._user && _this._user.userCompanies.length > 0) {
                    for (var k = 0; k < _this._user.userCompanies.length ; k++) {
                        if (_this._user.userCompanies[k].preferences && _this._user.userCompanies[k].preferences.length > 0) {
                            for (var j = 0; j < _this._user.userCompanies[k].preferences.length ; j++) {
                                for (var i = 0; i < dataPref.length ; i++) {
                                    if (dataPref[i].preferenceId == _this._user.userCompanies[k].preferences[j].preferenceId) {
                                        // si no tiene valor almacenado, le agrega el default
                                        if (_this._user.userCompanies[k].preferences[j].value == "" || _this._user.userCompanies[k].preferences[j].value == undefined) {
                                            _this._user.userCompanies[k].preferences[j].value = dataPref[i].defaultValue;
                                        }
                                        break;
                                    } else if (i + 1 == dataPref.length) {
                                        _this._user.userCompanies[k].preferences.push(dataPref[i]);
                                    }
                                }
                            }
                        } else {
                            for (var h = 0; h < dataPref.length ; h++) {
                                _this._user.userCompanies[k].preferences[h] = {
                                    value: dataPref[h].defaultValue,
                                    moduleId: dataPref[h].moduleId,
                                    preferenceId: dataPref[h].preferenceId
                                }
                            }
                        }
                    }
                }
                // Mostrar preferencias segun el modulo seleccionado
                _this.changeList(_this._prevSel);
            });
        },
        reRender: function () {
            var _this = this;

            _this.saveCurrentItems(function () {
                var slctdPrefMod = {
                    companyId: $("div[data-id='" + _this._uId + "']").find("div.combo-company-selection select").val(),
                    moduleId: $("div[data-id='" + _this._uId + "']").find("div.pref-module-selection select").val()
                }
                var divPrefContent = $("div[data-id='" + _this._uId + "']").find("div.pref-content").children();
                if ($(divPrefContent).length > 0) {
                    $(divPrefContent).fadeOut(100, "linear", function () {
                        _this.changeList(slctdPrefMod);
                    });
                } else
                    _this.changeList(slctdPrefMod);
            });
        },
        saveCurrentItems: function (callback) {
            var _this = this;
            var prefList = $("div[data-id='" + _this._uId + "']").find("div.pref-content input");

            // Carga datos del formulario actual en arreglo auxiliar.
            if (prefList.length > 0) {
                var auxList = [{}];
                for (var i = 0; i < prefList.length ; i++) {
                    auxList[i] = {
                        preferenceId: $(prefList[i]).attr("data-id"),
                        value: prefList[i].value,
                        moduleId: _this._prevSel.moduleId
                    }
                }
                // actualiza preferencias                
                if (auxList.length > 0) {
                    for (var j = 0; j < _this._user.userCompanies.length ; j++) {
                        if (_this._user.userCompanies[j].companyId == _this._prevSel.companyId) {
                            if (_this._user.userCompanies[j].preferences.length > 0) {
                                for (var i = 0; i < auxList.length ; i++) {
                                    for (var k = 0; k < _this._user.userCompanies[j].preferences.length ; k++) {
                                        if (_this._user.userCompanies[j].preferences[k].preferenceId == auxList[i].preferenceId) {
                                            _this._user.userCompanies[j].preferences[k].value = auxList[i].value;
                                            break;
                                        } else if (k + 1 == _this._user.userCompanies[j].preferences.length) {
                                            _this._user.userCompanies[j].preferences.push(auxList[i]);
                                        }
                                    }
                                }
                            } else {
                                _this._user.userCompanies[j].preferences = auxList;
                            }
                        }
                    }
                }
            }
            callback();
        },
        changeList: function (selectedCombos) {
            var _this = this;
            var prefMod = new prefModel();

            prefMod.List(selectedCombos.moduleId, function (dataPref) {
                var prefTemplate = Handlebars.compile(PrefTmp);
                
                for (var i = 0; i < _this._user.userCompanies.length ; i++) {
                    if (_this._user.userCompanies[i].companyId == selectedCombos.companyId) {
                        for (var j = 0; j < dataPref.length ; j++) {
                            for (var k = 0; k < _this._user.userCompanies[i].preferences.length ; k++) {
                                if (dataPref[j].preferenceId == _this._user.userCompanies[i].preferences[k].preferenceId) {
                                    dataPref[j].defaultValue = _this._user.userCompanies[i].preferences[k].value;
                                    break;
                                }
                            }
                        }
                    }
                }

                var dataPrefItemTemplate = {
                    data: dataPref
                };
                var html = prefTemplate(dataPrefItemTemplate);
                
                var divPrefContent = $("div[data-id='" + _this._uId + "']").find("div.pref-content");
                $(divPrefContent).children().remove();
                $(divPrefContent).append(html);
                $(divPrefContent).children().fadeIn(100, "linear", function () {

                });
                _this._prevSel = {
                    companyId: __currentSession.companyId,
                    moduleId: selectedCombos.moduleId
                }
            });
        },
        save: function () {
            var _uId = this._uId;
            var _this = this;
            var usrMod = new userModel();

            _this.saveCurrentItems(function () {
                usrMod.Update(_this._user, function () {
                    require(['controllers/abmManagers/userManager'], function (Controller) {
                        (new Controller()).show();
                    });
                })
            });
        },
        cancel: function () {
            require(['controllers/abmManagers/userManager'], function (Controller) {
                (new Controller()).show();
            });
        },
        addHandlers: function () {
            $("div[data-id='" + this._uId + "']").find("form").on("submit", $.proxy(function () {
                this.save();
                return false;
            }, this));
            $("div[data-id='" + this._uId + "']").find("div.submit button.btn-cancel").on("click", $.proxy(function () {
                this.cancel();
                return false;
            }, this));
            $("div[data-id='" + this._uId + "']").find("div.pref-module-selection select").on("change", $.proxy(function () {
                this.reRender();
                return false;
            }, this));
            $("div[data-id='" + this._uId + "']").find("div.combo-company-selection select").on("change", $.proxy(function () {
                this.reRender();
                return false;
            }, this));
            $("div[data-id='" + this._uId + "']").find("div.abm-top-options a.btn-close").on("click", this.cancel);
        }
    });
    return view;
});